#include "Level.h"
#include "RessourceManager.h"
#include "Constants.h"
#include <fstream>

Level::Level()
{
    w = h = 0;
    tileset = 0;
    outTile = 0;

    data = NULL;
}

Level::Level(int w, int h)
{
    create(w, h);

    tileset = 0;
    outTile = 0;
}

void Level::create(int w, int h)
{
    this->w = w;
    this->h = h;

    data = new unsigned char*[w];
    sprites = new sf::Sprite*[w];
    for(int i=0; i<w; i++)
    {
        data[i] = new unsigned char[h];
        sprites[i] = new sf::Sprite[h];
        for(int j=0; j<h; j++)
        {
            data[i][j] = 0;
            sprites[i][j].setPosition(i*TILE_SIZE, -(j+1)*TILE_SIZE);
            sprites[i][j].setTexture(*RessourceManager::getTexture("tileset.png"));
        }
    }
}

void Level::loadFromFile(std::string f)
{
    std::fstream file;
    file.open(f.c_str(), std::ios::binary | std::ios::in);

    if(file.is_open())
    {
        file.read((char*)&w, 4);
        file.read((char*)&h, 4);
        file.read((char*)&tileset, 1);
        file.read((char*)&outTile, 1);

        create(w, h);

        for(int j=0; j<h; j++)
        {
            for(int i=0;i<w; i++)
            {
                file.read((char*)&data[i][j], 1);
                sprites[i][j].setTextureRect(sf::IntRect(data[i][j]%16 * TILE_SIZE, data[i][j]/16*TILE_SIZE, TILE_SIZE, TILE_SIZE));
            }
        }
    }
    else
    {
        std::cout << "Error opening " << f << ".\n";
    }
}

unsigned char Level::getTexture(int x, int y)
{
    return (x>=0 && x<w && y>=0 && y<h ? data[x][y] : outTile);
}

sf::Sprite* Level::getSprite(int x, int y)
{
    return &sprites[x][y];
}

int Level::getWidth()
{
    return w;
}

int Level::getHeight()
{
    return h;
}
